package com.jasonchoi.security.commons.security;

import com.jasonchoi.security.entity.Permission;
import com.jasonchoi.security.entity.Role;
import com.jasonchoi.security.repository.PermissionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * @Author: JasonChoi
 * @Date: 2020/1/7 11:40
 */
@Service
public class MyInvocationSecurityMetadataSourceService  implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private PermissionRepository permissionDao;

    //此方法是为了判定用户请求的url 是否在权限表中，如果在权限表中，则返回给 decide 方法，用来判定用户是否有此权限。如果不在权限表中则放行。
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        Permission permission = permissionDao.findByPermission(requestUrl);
        if (Objects.isNull(permission)){
            return null;
        }
        List<Role> roleList = permission.getRoleList();
        String[] names = new String[roleList.size()];
        for (int i = 0; i < roleList.size(); i++) {
            names[i] = roleList.get(i).getName();
        }
        return SecurityConfig.createList(names);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}